package com.mibus.mibusmobile;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import android.view.View.OnKeyListener;
import android.view.View.OnClickListener;


public class RastreoActivity extends Activity implements OnClickListener, OnKeyListener,AdapterView.OnItemSelectedListener {

    private TextView tvCedulas;
    private Button btnDetenerRecorrido;
    private Button btnAgregarEvento;
    private Button btnEvento;
    private Button btnCancelarAgregarEvento;
    private Spinner spEventos;
    private EditText etCedulas;
    private Button btnSaltarParada;
    private Button btnSinCedula;

    private String id_recorrido_realizado = "";
    private String hash_session = "";
    private String cedula = "";
    private String id_bus = "";
    private String id_conductor = "";

    private double update_time=0;

    private long MIN_TIME=0;

    private JSONArray jsonEventos = new JSONArray();
    private Integer id_evento = null;
    private PowerManager.WakeLock mWakeLock;
    private GpsService gpsService;
    private final String MOBILE_APP_URL = "http://mibus.eia.edu.co/Tablet/";
    private ErrorLog log;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondactivitymibuscopia);

        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();

        tvCedulas = (TextView) findViewById(R.id.tvCedulas);
        btnDetenerRecorrido = (Button)findViewById(R.id.btnDetenerR);
        etCedulas = (EditText)findViewById(R.id.etCedulas);
        btnAgregarEvento = (Button) findViewById(R.id.btnAgregarEvento);
        spEventos = (Spinner) findViewById(R.id.spEventos);
        btnEvento = (Button) findViewById(R.id.btnEvento);
        btnCancelarAgregarEvento = (Button) findViewById(R.id.btnCancelarAgregarEvento);
        btnSaltarParada = (Button) findViewById(R.id.btnSaltarParada);
        btnSinCedula = (Button) findViewById(R.id.btnSinCedula);

        spEventos.setVisibility(View.INVISIBLE);
        spEventos.setEnabled(false);
        btnAgregarEvento.setVisibility(View.INVISIBLE);
        btnAgregarEvento.setEnabled(false);
        btnCancelarAgregarEvento.setVisibility(View.INVISIBLE);
        btnCancelarAgregarEvento.setEnabled(false);

        etCedulas.setOnKeyListener(this);
        btnDetenerRecorrido.setOnClickListener(this);
        btnAgregarEvento.setOnClickListener(this);
        btnEvento.setOnClickListener(this);
        btnCancelarAgregarEvento.setOnClickListener(this);
        btnSaltarParada.setOnClickListener(this);
        btnSinCedula.setOnClickListener(this);


        Bundle bundleReceptor2 = getIntent().getExtras();
        id_recorrido_realizado = bundleReceptor2.getString("id_recorrido_realizado");
        hash_session = bundleReceptor2.getString("hash_session");
        id_bus = bundleReceptor2.getString("id_bus");
        id_conductor = bundleReceptor2.getString("id_conductor");

        try{
            update_time = Double.parseDouble(bundleReceptor2.getString("update_time"));
            Double temp = 1000 * update_time;
            MIN_TIME = temp.longValue();
        }catch (Exception e){
            MIN_TIME=1000;
        }
        log =  new ErrorLog("RecorridoRealizadoActivity"+id_recorrido_realizado);
        requestEventos();
        gpsService =  new GpsService(this, MIN_TIME, hash_session, id_recorrido_realizado);
        gpsService.usarGPS();
    }

    @Override
    protected void onDestroy() {
        this.mWakeLock.release();
        gpsService.dejarUsarGPS();
        gpsService.finalizar();
        log.generarArchivoLog();
        super.onDestroy();
    }

    /*public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        TextView tvProximaParada = (TextView) findViewById(R.id.tvProximaParada);
        TextView tvProximaParadaReservas = (TextView) findViewById(R.id.tvProximaParadaReservas);

        TextView tvProximaParada1 = (TextView) findViewById(R.id.tvProximaParada1);
        TextView tvProximaParada2 = (TextView) findViewById(R.id.tvProximaParada2);
        TextView tvPuestosDisponibles = (TextView) findViewById(R.id.tvPuestosDisponibles);
        TextView tvOcupados = (TextView) findViewById(R.id.tvOcupados);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            String pp =
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }*/

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btnDetenerR){
            btnEvento.setEnabled(false);
            btnSaltarParada.setEnabled(false);
            btnDetenerRecorrido.setEnabled(false);
            AlertDialog.Builder detenerRDialog = new AlertDialog.Builder(this);
            detenerRDialog.setTitle("Detener Recorrido");
            detenerRDialog.setMessage("¿Esta seguro que desea finalizar el recorrido?");

            detenerRDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    try{
                        List<NameValuePair> nameValuePairsFinalizar=new ArrayList<NameValuePair>();
                        nameValuePairsFinalizar.add(new BasicNameValuePair("tag", "FINALIZAR"));
                        nameValuePairsFinalizar.add(new BasicNameValuePair("hash_session", hash_session));
                        nameValuePairsFinalizar.add(new BasicNameValuePair("id_recorrido_realizado", id_recorrido_realizado));
                        RequestPost requestFinalizar = new RequestPost(nameValuePairsFinalizar, RastreoActivity.this);

                        String resultado = requestFinalizar.execute(MOBILE_APP_URL+"finalizar_recorrido").get();
                        Log.i("Resultado", resultado);
                        if (!resultado.equals("NoInternet")) {
                            JSONObject returnArray = new JSONObject(resultado);
                            if (!returnArray.getBoolean("error")) {//if(resultado.equals("1")){
                                gpsService.dejarUsarGPS();
                                Toast.makeText(getApplicationContext(), "Se ha finalizado el recorrido correctamente", Toast.LENGTH_SHORT).show();

                                gpsService.dejarUsarGPS();
                                gpsService.finalizar();
                                log.generarArchivoLog();
                                Intent intent1 = new Intent(RastreoActivity.this, RecorridoActivity.class);
                                Bundle bundleEmisor2 = new Bundle();

                                bundleEmisor2.putString("hash_session", hash_session);
                                bundleEmisor2.putString("update_time", String.valueOf(update_time));
                                bundleEmisor2.putString("id_bus", id_bus);
                                bundleEmisor2.putString("id_conductor", id_conductor);

                                intent1.putExtras(bundleEmisor2);
                                MySQLiteHelperRecorrido dbHelper = new MySQLiteHelperRecorrido(RastreoActivity.this);
                                dbHelper.eliminarRecorrido(1);
                                RastreoActivity.this.finish();
                            } else {
                                log.agregarLog(returnArray.getString("errorDesc"));
                            }
                        }
                    }catch (Exception e){
                        //tvInformacion.setText("Ha ocurrido un error al finalizar el recorrido");
                        log.agregarLog("Problemas al finalizar el recorrido en la aplicacion");
                    }
                    btnEvento.setEnabled(true);
                    btnSaltarParada.setEnabled(true);
                    btnDetenerRecorrido.setEnabled(true);
                    etCedulas.requestFocus();
                }
            });

            detenerRDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    etCedulas.requestFocus();
                    btnEvento.setEnabled(true);
                    btnSaltarParada.setEnabled(true);
                    btnDetenerRecorrido.setEnabled(true);
                }});
            detenerRDialog.show();

        }
        if(view.getId()==R.id.btnEvento){
            btnDetenerRecorrido.setEnabled(false);
            btnEvento.setEnabled(false);
            btnSaltarParada.setEnabled(false);
            btnSinCedula.setEnabled(false);
            btnSinCedula.setVisibility(View.INVISIBLE);

            etCedulas.setEnabled(false);
            etCedulas.setVisibility(View.INVISIBLE);
            tvCedulas.setVisibility(View.INVISIBLE);

            spEventos.setVisibility(View.VISIBLE);
            spEventos.setEnabled(true);
            btnAgregarEvento.setVisibility(View.VISIBLE);
            btnAgregarEvento.setEnabled(true);
            btnCancelarAgregarEvento.setVisibility(View.VISIBLE);
            btnCancelarAgregarEvento.setEnabled(true);
        }
        if(view.getId()==R.id.btnAgregarEvento){
            try{
                double latitud = gpsService.getLocation().getLatitude();
                double longitud = gpsService.getLocation().getLongitude();
                List<NameValuePair> nameValuePairsEvento = new ArrayList<NameValuePair>();
                nameValuePairsEvento.add(new BasicNameValuePair("tag", "EVENTO"));
                nameValuePairsEvento.add(new BasicNameValuePair("hash_session", hash_session));
                nameValuePairsEvento.add(new BasicNameValuePair("id_recorrido_realizado", id_recorrido_realizado));
                nameValuePairsEvento.add(new BasicNameValuePair("id_evento", id_evento.toString()));
                nameValuePairsEvento.add(new BasicNameValuePair("latitud", String.valueOf(latitud)));
                nameValuePairsEvento.add(new BasicNameValuePair("longitud", String.valueOf(longitud)));
                RequestPost requestPostEventos = new RequestPost(nameValuePairsEvento, this);

                String resultado= requestPostEventos.execute(MOBILE_APP_URL+"agregar_evento").get();
                Log.i("Resultado", resultado);
                if (!resultado.equals("NoInternet")) {
                    JSONObject returnArray = new JSONObject(resultado);
                    if (!returnArray.getBoolean("error")) {//if(resultado.equals("1")){
                        Toast.makeText(getApplicationContext(), "Se ha agregado correctamente el evento", Toast.LENGTH_SHORT).show();
                        btnDetenerRecorrido.setEnabled(true);
                        btnEvento.setEnabled(true);
                        btnSaltarParada.setEnabled(true);
                        btnSinCedula.setEnabled(true);
                        btnSinCedula.setVisibility(View.VISIBLE);

                        etCedulas.setEnabled(true);
                        etCedulas.setVisibility(View.VISIBLE);
                        tvCedulas.setVisibility(View.VISIBLE);

                        spEventos.setVisibility(View.INVISIBLE);
                        spEventos.setEnabled(false);
                        btnAgregarEvento.setVisibility(View.INVISIBLE);
                        btnAgregarEvento.setEnabled(false);
                        btnCancelarAgregarEvento.setVisibility(View.INVISIBLE);
                        btnCancelarAgregarEvento.setEnabled(false);

                        etCedulas.requestFocus();
                    } else {
                        Toast.makeText(getApplicationContext(), "Hubo un error al agregar el evento", Toast.LENGTH_SHORT).show();
                        log.agregarLog(returnArray.getString("errorDesc"));
                        etCedulas.requestFocus();
                    }
                }
            }catch (Exception e){
                Toast.makeText(getApplicationContext(),"Ha ocurrido un error al agregar el evento intente de nuevo",Toast.LENGTH_SHORT).show();
                etCedulas.requestFocus();
            }
        }
        if(view.getId()==R.id.btnCancelarAgregarEvento){
            btnDetenerRecorrido.setEnabled(true);
            btnEvento.setEnabled(true);
            btnSaltarParada.setEnabled(true);
            btnSinCedula.setEnabled(true);
            btnSinCedula.setVisibility(View.VISIBLE);

            etCedulas.setEnabled(true);
            etCedulas.setVisibility(View.VISIBLE);
            tvCedulas.setVisibility(View.VISIBLE);

            spEventos.setVisibility(View.INVISIBLE);
            spEventos.setEnabled(false);
            btnAgregarEvento.setVisibility(View.INVISIBLE);
            btnAgregarEvento.setEnabled(false);
            btnCancelarAgregarEvento.setVisibility(View.INVISIBLE);
            btnCancelarAgregarEvento.setEnabled(false);
            etCedulas.requestFocus();
        }
        if(view.getId() == R.id.btnSaltarParada){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        List<NameValuePair> nameValuePairsSaltar = new ArrayList<NameValuePair>();
                        nameValuePairsSaltar.add(new BasicNameValuePair("id_recorrido_realizado",id_recorrido_realizado));
                        nameValuePairsSaltar.add(new BasicNameValuePair("hash_session", hash_session));
                        RequestPost requestPostSaltar = new RequestPost(nameValuePairsSaltar, RastreoActivity.this);
                        final String resultado = requestPostSaltar.execute(MOBILE_APP_URL+"saltar_parada").get();
                        Log.i("Resultado", resultado);
                        if (!resultado.equals("NoInternet")) {
                            JSONObject jsonObject = new JSONObject(resultado);
                            if (!jsonObject.getBoolean("error")) {
                                final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.parada_saltada);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            } else if (jsonObject.getString("tipo").equals("1")) {
                                final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.saltar_parada_no_puede);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            } else if (jsonObject.getString("tipo").equals("2")) {
                                log.agregarLog("error al saltar la parada en el metodo saltar_parada del servidor, puede que se dirija a la parada final");//jsonObject.getString("errorDesc"));
                                final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.error_saltando_parada);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            }else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(RastreoActivity.this, resultado, Toast.LENGTH_LONG).show();
                                    }
                                });
                                log.agregarLog(resultado);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        final Exception e2 = e;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RastreoActivity.this, "error "+e2.toString(), Toast.LENGTH_LONG).show();
                            }
                        });
                        log.agregarLog(e.toString());
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        r.play();
                    }
                }
            }).start();

            etCedulas.requestFocus();
        }
        if(view.getId() == R.id.btnSinCedula){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<NameValuePair> nameValuePairsCedula = new ArrayList<NameValuePair>();
                        nameValuePairsCedula.add(new BasicNameValuePair("hash_session", hash_session));
                        nameValuePairsCedula.add(new BasicNameValuePair("id_recorrido_realizado", id_recorrido_realizado));
                        nameValuePairsCedula.add(new BasicNameValuePair("id_bus", id_bus));
                        RequestPost requestPostCedula = new RequestPost(nameValuePairsCedula, RastreoActivity.this);

                        final String result = requestPostCedula.execute(MOBILE_APP_URL+"aumentar_puestos_ocupados_sin").get();
                        Log.i("Resultado", result);
                        if (!result.equals("NoInternet")) {
                            if (result.equals("1")) {                   //1 => hay puestos y puede ingresar
                                final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.puede_ingresar);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            } else if (result.equals("0")) {             //0 => el bus no tiene puestos
                                log.agregarLog("Error al saltar cedula el bus no tiene puestos");
                                try {
                                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                    r.play();
                                } catch (Exception e) {
                                }
                            } else if (result.equals("2")) {            //2 =>el bus no tiene puestos
                                final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.no_puede_ingresar);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            } else {
                                //Hubo un error en el servidor
                                log.agregarLog("Hubo un error en el servidor en el metodo aumentar_puestos_ocupados_sin");
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(RastreoActivity.this, result, Toast.LENGTH_LONG).show();
                                    }
                                });
                                try {
                                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                    r.play();
                                } catch (Exception e) {
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.agregarLog("Error ingresando la cedula en la aplicacion");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RastreoActivity.this, "Ha ocurrido un error al ingresar cedula intentelo de nuevo", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }).start();
            etCedulas.requestFocus();
        }
    }

    public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
        if(keyEvent.getAction()== KeyEvent.ACTION_UP && keycode == KeyEvent.KEYCODE_ENTER && view.getId()== R.id.etCedulas){
            cedula = etCedulas.getText().toString();
            cedula = cedula.replace("a","");
            if(!cedula.equals("")){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            List<NameValuePair> nameValuePairsCedula = new ArrayList<NameValuePair>();
                            nameValuePairsCedula.add(new BasicNameValuePair("tag", "CEDULA"));
                            nameValuePairsCedula.add(new BasicNameValuePair("hash_session", hash_session));
                            nameValuePairsCedula.add(new BasicNameValuePair("id_recorrido_realizado", id_recorrido_realizado));
                            nameValuePairsCedula.add(new BasicNameValuePair("cedula", cedula));
                            nameValuePairsCedula.add(new BasicNameValuePair("id_bus", id_bus));
                            RequestPost requestPostCedula = new RequestPost(nameValuePairsCedula, RastreoActivity.this);

                            final String result = requestPostCedula.execute(MOBILE_APP_URL+"verificar_cedula").get();
                            Log.i("Resultado", result);
                            if (!result.equals("NoInternet")) {
                                if (result.equals("1") || result.equals("4")) {                   //1 => Cedula identificada                  4 =>cedula ya ha sido ingresada
                                    final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.puede_ingresar);
                                    try {
                                        mp.start();
                                    } catch (Exception e) {
                                    }
                                } else if (result.equals("2") || result.equals("3")) {             //2o3 =>Ocurrio un error al ingresar la cedula
                                    log.agregarLog("Error ingresando la cedula en el metodo verificar_cedula");
                                    try {
                                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                        r.play();
                                    } catch (Exception e) {
                                    }
                                } else if (result.equals("-1") || result.equals("0")) {            //-1 =>El bus no tiene puestos libres       0 =>Cedula no identificada
                                    final MediaPlayer mp = MediaPlayer.create(RastreoActivity.this, R.raw.no_puede_ingresar);
                                    try {
                                        mp.start();
                                    } catch (Exception e) {
                                    }
                                } else {
                                    //Hubo un error en el servidor
                                    log.agregarLog("Error ingresando la cedula en el metodo verificar_cedula");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RastreoActivity.this, result, Toast.LENGTH_LONG).show();
                                        }
                                    });
                                    try {
                                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                        r.play();
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.agregarLog("Error ingresando la cedula en la aplicacion");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RastreoActivity.this, "Ha ocurrido un error al ingresar cedula intentelo de nuevo", Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }).start();
                etCedulas.setText("");
                etCedulas.requestFocus();
            }
            etCedulas.requestFocus();
            return true;
        }else{
            return false;
        }
    }


    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        Spinner spinner = (Spinner)adapterView;
        String selectedItem= adapterView.getItemAtPosition(pos).toString();
        if(spinner.getId()==R.id.spEventos){
            if(pos!=0){
                try{
                    for(int i=0;i< jsonEventos.length();i++){
                        JSONObject JSONobjeto = jsonEventos.getJSONObject(i);
                        JSONObject  JSONevento= JSONobjeto.getJSONObject("Evento");
                        if(JSONevento.getString("nombre_evento").equals(selectedItem)){
                            id_evento=JSONevento.getInt("id_evento");
                        }
                    }
                }catch (Exception e){
                }
            }else{
                id_evento=null;
            }
        }
    }

    public void onNothingSelected(AdapterView<?> adapterView) {}

    public void requestEventos(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    RequestGet requestGetEventos= new RequestGet(RastreoActivity.this);
                    String resultado = requestGetEventos.execute(MOBILE_APP_URL+"eventos_get?hash_session="+hash_session).get();
                    if (!resultado.equals("NoInternet")) {
                        jsonEventos = new JSONArray(resultado);
                        //jsonEventos =RGEventos.execute(MOBILE_APP_URL+"eventos_get?hash_session="+hash_session).get();
                        List<String> contenidoSpinner = new ArrayList<String>();
                        contenidoSpinner.add("Seleccionar Evento");
                        for (int i = 0; i < jsonEventos.length(); i++) {
                            JSONObject JSONobjeto = jsonEventos.getJSONObject(i);
                            JSONObject JSONevento = JSONobjeto.getJSONObject("Evento");
                            contenidoSpinner.add(JSONevento.getString("nombre_evento"));
                        }
                        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(RastreoActivity.this,
                                R.layout.spinner_item, contenidoSpinner);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                spEventos.setAdapter(adapter);
                                spEventos.setOnItemSelectedListener(RastreoActivity.this);
                            }
                        });

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RastreoActivity.this, "No hay conexion a internet, no se pudo obtener los eventos", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }catch (Exception e){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RastreoActivity.this, "No se pudo obtener los eventos", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    public void onBackPressed() {
        Toast.makeText(getApplicationContext(),"No puede salir aun no ha finalizado el recorrido",Toast.LENGTH_SHORT).show();
    }

}